<?php
declare(strict_types=1);

namespace app\model;

use app\model\scope\ScopeName;
use think\Model;

/**
 * @property int $id
 * @property string $name 插件名称
 * @property string $author 作者
 * @property string $introduction 简介
 * @property \DateTime $create_time 创建时间
 * @property \DateTime $update_time 更新时间
 * @property string $version 版本
 * @property int $status 状态：0待安装 1已安装 2安装中
 */
class Plugs extends Model
{
    use ScopeName;

    // 插件状态
    const STATUS_PENDING = 0; // 待安装
    const STATUS_INSTALLED = 1; // 已安装
    const STATUS_INSTALLING = 2; // 安装中

    protected $schema = [
        'id' => 'int',
        'name' => 'string',
        'author' => 'string',
        'introduction' => 'string',
        'create_time' => 'datetime',
        'update_time' => 'datetime',
        'version' => 'string',
        'status' => 'int',
    ];

    // 自动时间戳
    protected $autoWriteTimestamp = 'datetime';
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';

    public function scopeInstalled($query)
    {
        return $query->where('status', self::STATUS_INSTALLED);
    }

    public function scopeInstalling($query)
    {
        return $query->where('status', self::STATUS_INSTALLING);
    }

    public function markAsInstalling(): bool
    {
        $this->status = self::STATUS_INSTALLING;
        return $this->save();
    }

    public function markAsInstalled(): bool
    {
        $this->status = self::STATUS_INSTALLED;
        return $this->save();
    }

    public function markAsPending(): bool
    {
        $this->status = self::STATUS_PENDING;
        return $this->save();
    }

    public function getDependencies(): array
    {
        return $this->dependencies ?? [];
    }

    public function addDependency(string $pluginName): bool
    {
        $dependencies = $this->getDependencies();
        if (!in_array($pluginName, $dependencies)) {
            $dependencies[] = $pluginName;
            $this->dependencies = $dependencies;
            return $this->save();
        }
        return true;
    }
}
